
import Foundation
import StoreKit
import Alamofire
import SwiftyStoreKit
import SwiftEventBus

class PurchaseManager: NSObject, SKProductsRequestDelegate, SKPaymentTransactionObserver {
    let productIDs = [
//        //测试

        "super.week",
        "super.month",
        "super.year"
    ]
    
    var fromPage: String! = ""
    func addFromPage(_ from: String?){
        fromPage = from ?? "续期订阅"
    }
    
    var catgptRequest: SKProductsRequest!
    var catgptProducts = [SKProduct]()
    var productList:[CatProduct] = []
    var completeHandler:( (SKPaymentTransactionState?) -> Void )?
    static let sharedInstance = PurchaseManager()
    func addCompleteHandler(_ handler: @escaping (SKPaymentTransactionState?) -> Void ){
        completeHandler = handler
    }
    
    func checkExpire(){
        //测试
//        let appleValidator = AppleReceiptValidator(service: .production, sharedSecret: "f50e6cee15fa4623a4c851e7080d5483")
        
        let appleValidator = AppleReceiptValidator(service: .production, sharedSecret: "b989cbe2fe3147fe8e8ccad0f2d19949")
        SwiftyStoreKit.verifyReceipt(using: appleValidator) { result in
            switch result {
            case .success(let receipt):
                var isValid = false
                for productId in self.productIDs {
                    // Verify the purchase of a Subscription
                    let purchaseResult = SwiftyStoreKit.verifySubscription(
                        ofType: .autoRenewable, // or .nonRenewing (see below)
                        productId: productId,
                        inReceipt: receipt)
                    
                    switch purchaseResult {
                    case .purchased(let expiryDate, let items):
                        isValid = isValid || true
                        print("\(productId) is valid until \(expiryDate)\n\(items)\n")
                    case .expired(let expiryDate, let items):
                        isValid = isValid || false
                        print("\(productId) is expired since \(expiryDate)\n\(items)\n")
                    case .notPurchased:
                        isValid = isValid || false
                        print("The user has never purchased \(productId)")
                    }
                }
                print("isValid=======\(isValid)")
                StoreManager.setVip(vip: isValid)
                SwiftEventBus.post(EVENT_NAME_REFRESH_VIP_STATE)
                
            case .error(let error):
                print("Receipt verification failed: \(error)")
            }
        }
    }
    
    func productsRequest(_ request: SKProductsRequest, didReceive response: SKProductsResponse) {
        if catgptProducts.isEmpty || catgptProducts.count != productIDs.count{
            var gptProducts = [SKProduct]()
            if !response.products.isEmpty {
                for fetchedProduct in response.products {
                    print("price=\(fetchedProduct.price)")
                    gptProducts.append(fetchedProduct)
                }
                DispatchQueue.main.async {
                    self.catgptProducts = gptProducts
                    if self.catgptProducts.count == 3{
                        var catProduct = CatProduct(productPrice: "\(self.weekPrice())元", originalPrice: "原价\((Int(self.weekPrice()) ?? 28) * 2)", productTitle: "周会员")
                        catProduct.isSelect = false
                        self.productList.append(catProduct)
                        catProduct = CatProduct(productPrice:  "\(self.yearPrice())元", originalPrice: "原价\((Int(self.yearPrice()) ?? 198) * 2)", productTitle: "年会员")
                        catProduct.isSelect = true
                        self.productList.append(catProduct)
                        
                        catProduct = CatProduct(productPrice:  "\(self.monthPrice())元", originalPrice: "原价\((Int(self.monthPrice()) ?? 98) * 2)", productTitle: "月会员")
                        catProduct.isSelect = false
                        self.productList.append(catProduct)
                    }
                   
                    SwiftEventBus.post(EVENT_NAME_PRODUCT_LOAD)
                }
            }
            
        }
        
    }
    
    func getChatGptProducts() {
        let request = SKProductsRequest(productIdentifiers: Set(productIDs))
        request.delegate = self
        request.start()
        
        if StoreManager.getCoins() > 0{
            addVipInfo(price: StoreManager.getCoins())
        }
    }
    
    
    
    
    
    func request(_ request: SKRequest, didFailWithError error: Error) {
    }
    
    @Published var transactionState: SKPaymentTransactionState?
    
    func restoreChatGptProducts() {
        SKPaymentQueue.default().restoreCompletedTransactions()
    }
    
    
    func paymentQueue(_ queue: SKPaymentQueue, updatedTransactions transactions: [SKPaymentTransaction]) {
        
        for transaction in transactions {
            switch transaction.transactionState {
            case .purchasing:
                transactionState = .purchasing
                if let handler = completeHandler{
                    handler(transactionState)
                }
            case .purchased:
                UserDefaults.standard.setValue(true, forKey: transaction.payment.productIdentifier)
                queue.finishTransaction(transaction)
                transactionState = .purchased
                if let handler = completeHandler{
                    handler(transactionState)
                }
                
                self.updateVipInfo(productId:transaction.payment.productIdentifier)
            case .restored:
                UserDefaults.standard.setValue(true, forKey: transaction.payment.productIdentifier)
                queue.finishTransaction(transaction)
                transactionState = .restored
                if let handler = completeHandler{
                    handler(transactionState)
                }
            case .failed, .deferred:
                print("failedddddd")
                queue.finishTransaction(transaction)
                transactionState = .failed
                if let handler = completeHandler{
                    handler(transactionState)
                }
            default:
                
                print("faileddddddee")
                queue.finishTransaction(transaction)
            }
        }
    }
    
    
    func updateVipInfo(productId: String){
        var price : Double = 0.0
        if catgptProducts.count == productIDs.count{
            for product in catgptProducts{
                if(product.productIdentifier == productId){
                    price = product.price.doubleValue
                }
            }
        }
        print("price=====\(price)")
//
        StoreManager.setCoins(coins: price)
        addVipInfo(price: price)
        
    }
    var coinsAdding = false
    func addVipInfo(price:Double){
        
        //修复重复提交的bug
        if !coinsAdding{
            coinsAdding = true
            let parameters = CoinsParameters(coins:price,fromPage: fromPage)
            
            AFManager.sharedInstance.manager.request("\(baseUrl)token/coins/updateV2",method: .post,parameters: parameters,encoder: URLEncodedFormParameterEncoder.default).responseString { response in
                if let string = response.value{
                    print(string)
                    let data = Data(string.utf8)
                    do {
                        let jsonDecoder = JSONDecoder()
                        let baseResponse = try jsonDecoder.decode(BaseResponse.self, from: data)
                        print("baseResponse=\(baseResponse.message)")
                        if baseResponse.code == 200{
                            StoreManager.setCoins(coins: 0)
                        }
                    } catch {
                    }
                    
                }else{
                    
                }
            }
        }
        DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 2){
            self.coinsAdding = false
        }
    }
    
    func weekPrice() -> String{
        var price = "28"
        if catgptProducts.count == productIDs.count{
            for product in catgptProducts{
                if(product.productIdentifier == productIDs[0]){
                    price = "\(product.price)"
                }
            }
        }
        return price
    }
    
    func monthPrice() -> String{
        var price = "88"
        if catgptProducts.count == productIDs.count{
            for product in catgptProducts{
                if(product.productIdentifier == productIDs[1]){
                    price = "\(product.price)"
                }
            }
        }
        return price
    }
    
    
    
    func yearPrice() -> String{
        var price = "198"
        if catgptProducts.count == productIDs.count{
            for product in catgptProducts{
                if(product.productIdentifier == productIDs[2]){
                    price = "\(product.price)"
                }
            }
        }
        return price
    }
    
    func weekPurchase(){
        if catgptProducts.count == productIDs.count{
            for product in catgptProducts{
                if(product.productIdentifier == productIDs[0]){
                    purchaseChatGptProduct(product: product)
                }
            }
        }
        
        
    }
    
    func monthPurchase(){
        if catgptProducts.count == productIDs.count{
            for product in catgptProducts{
                if(product.productIdentifier == productIDs[1]){
                    purchaseChatGptProduct(product: product)
                }
            }
        }
        
        
    }
    
    
    
    func yearPurchase(){
        if catgptProducts.count == productIDs.count{
            for product in catgptProducts{
                if(product.productIdentifier == productIDs[2]){
                    purchaseChatGptProduct(product: product)
                }
            }
        }
    }
    func purchaseChatGptProduct(product: SKProduct) {
        if SKPaymentQueue.canMakePayments() {
            let payment = SKPayment(product: product)
            SKPaymentQueue.default().add(payment)
        } else {
        }
    }
    
}
